var gh = (function() {

  var userId;
  var user_info_div;
  var timestamp;
  var num;
  const letters = new Set();
  var set= new Set();

    return {
    onload: function () {
        getDataFromCache();
        getChangeBodyButton();
        setImagesPX();
    }
  };
    function setImagesPX() {
        chrome.storage.local.get(['bodyPX'], function(result) {
            var px=result.bodyPX;
           if(px===undefined){
               px=320;
           }
            num = px / 80 - 1;
            chrome.storage.local.set({gameId: px / 80+"*"+px / 80}, function () {
            });
            timestamp = Date.parse(new Date());
            // timestamp = new Date().getTime();
            document.onmousemove = mouseMove;
            user_info_div = document.querySelector('#user_info');
            var xLetters = [0, 80, 160, 240, 320];
            var yLetters = [140, 220, 300, 380, 460];
            var h = 1;
            for (let a = 0; a < 10; a++) {
                if (letters.size < 3) {
                    let x = Math.round(Math.random() * num);
                    let y = Math.round(Math.random() * num);
                    if (!letters.has(xLetters[x] + "-" + yLetters[y])) {
                        letters.add(xLetters[x] + "-" + yLetters[y]);
                        document.getElementById("image" + h).style.top = yLetters[y] + "px";
                        document.getElementById("image" + h).style.left = xLetters[x] + "px";
                        h++;
                    }
                }
            }
        });
    }


    function getChangeBodyButton() {
        fourButton = document.querySelector('#four');
        fourButton.onclick = four;
        threeButton = document.querySelector('#three');
        threeButton.onclick = three;
        fiveButton = document.querySelector('#five');
        fiveButton.onclick = five;
        resetScoreButton = document.querySelector('#resetScore');
        resetScoreButton.onclick = resetScore;
        changeNameButton = document.querySelector('#changeName');
        changeNameButton.onclick = changeUserName;
    }
    function three() {
        document.body.style.width="240px";
        document.body.style.height="340px";
        num=2;
        document.getElementById("images").innerHTML="";
        document.getElementById("three").style.display="none";
        document.getElementById("four").style.display="";
        document.getElementById("five").style.display="";
        chrome.storage.local.set({bodyPX: "240"}, function () {
        });
        getGameRank("3*3");
    }
    function four() {
        document.body.style.width="320px";
        document.body.style.height="420px";
        num=3;
        document.getElementById("images").innerHTML="";
        document.getElementById("four").style.display="none";
        document.getElementById("three").style.display="";
        document.getElementById("five").style.display="";
        chrome.storage.local.set({bodyPX: "320"}, function () {
        });
        getGameRank("4*4");

    }
    function five() {
        document.body.style.width="400px";
        document.body.style.height="500px";
        num=4;
        document.getElementById("images").innerHTML='';
        document.getElementById("five").style.display="none";
        document.getElementById("four").style.display="";
        document.getElementById("three").style.display="";
        chrome.storage.local.set({bodyPX: "400"}, function () {
        });
        getGameRank("5*5");
    }
    function mouseMove(ev)
    {
        var xy = [];
        var i=0;
        for(let key of letters.keys()) {
          xy[i]=key;
          i++
        }
        f(xy[0],ev,0);
        f(xy[1],ev,1);
        f(xy[2],ev,2);
    }

    function f(key,ev,icon) {
        Ev= ev || window.event;
        var mousePos = mouseCoords(ev);
        //获取当前的x,y坐标
        var timest=Date.parse(new Date());
        // let timest = new Date().getTime();
        let x =Number(key.split("-")[0]) ;
        let y =Number(key.split("-")[1]) ;
        if (mousePos.x > x && mousePos.x < x+80 && mousePos.y > y && mousePos.y < y+80 && timest === timestamp) {
            addGameScore();
            g(icon);
            var music = document.createElement('div');
            music.innerHTML = "<audio autoplay=\"autoplay\"> <source src=\"" + "images/13172.mp3" + "\"type=\"audio/mpeg\"> </audio>";
            user_info_div.appendChild(music);
        }

    }
    function g(value) {
        if(!set.has(timestamp)){
        chrome.storage.local.get(['userId'], function(resul) {
            if (resul.userId!==undefined){
        chrome.storage.local.get(['icon0'], function(result) {
            chrome.storage.local.get(['icon1'], function(resultt) {
                chrome.storage.local.get(['icon2'], function(resulttt) {
                    var a=result.icon0;
                    var b=resultt.icon1;
                    var c=resulttt.icon2;
                    if (a===undefined){
                        chrome.storage.local.set({icon0: 0}, function () {
                        });
                        a=0;
                    }
                    if (b===undefined){
                        chrome.storage.local.set({icon1: 0}, function () {
                        });
                        b=0;
                    }
                    if (c===undefined){
                        chrome.storage.local.set({icon2: 0}, function () {
                        });
                        c=0;
                    }
                    if (value===0){
                         a++;
                         document.getElementById("icon").innerText="诺尔儿："+a+" 刻晴："+b+"  神里凌华："+c;
                         chrome.storage.local.set({icon0: a}, function () {
                         });

        }
        if (value===1){
                b++;
            document.getElementById("icon").innerText="诺尔儿："+a+" 刻晴："+b+"  神里凌华："+c;
            chrome.storage.local.set({icon1: b}, function () {
            });
        }
        if (value===2){
            c++;
            document.getElementById("icon").innerText="诺尔儿："+a+" 刻晴："+b+"  神里凌华："+c;
            chrome.storage.local.set({icon2: c}, function () {
            });
        }
         });
            });
        });}
        });
        set.add(timestamp);

    }
        setTimeout(z,1000);
    }
    function z() {
        console.log("我永远爱你");
    }

    function mouseCoords(ev)
    {
        //鼠标移动的位置
        if(ev.pageX || ev.pageY){
            return {x:ev.pageX, y:ev.pageY};
        }
        return{
            x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
            y:ev.clientY + document.body.scrollTop - document.body.clientTop
        };
    }
    function changeUserName() {
        qixia('GET', 'http://101.34.184.45/getNickName',
            false, changeName);
    }
    function resetGameScore() {
        chrome.storage.local.get(['userId'], function(result) {
            qixia('GET', 'http://101.34.184.45/resetGameScore/'+result.userId,
                false, qi);
        });
    }
    function getGameRank(id) {
        chrome.storage.local.get(['userId'], function(result) {
            qixia('GET', 'http://101.34.184.45/getGameRank/' + result.userId + '/' + id,
                false, getGameRankRs);
        });
    }
    function resetScore() {
        chrome.storage.local.set({icon0: 0}, function () {
        });
        chrome.storage.local.set({icon1: 0}, function () {
        });
        chrome.storage.local.set({icon2: 0}, function () {
        });
        chrome.storage.local.set({score: 0}, function () {
        });
        document.getElementById("icon").innerText= "诺尔儿：0 刻晴：0  神里凌华：0";
        chrome.storage.local.get(['bodyPX'], function(resultttt) {
            num = resultttt.bodyPX / 80 - 1;
            document.getElementById("details2").innerText =
                "难度：" + resultttt.bodyPX / 80 + "*" + resultttt.bodyPX / 80 + " " +
                "总数: 0     排行榜: ";
            resetGameScore();
        });

    }
    function changeName(error, status, response) {
            if (!error && status == 200) {
                var result = JSON.parse(response);
                chrome.storage.local.set({userId: result}, function () {
                });
                document.getElementById("details1").innerText=
                    "昵称："+result;
                document.getElementById("changeName").style.visibility="hidden";
            }

    }

    function addGameScore() {
        chrome.storage.local.get(['gameId'], function(result) {
            chrome.storage.local.get(['userId'], function(resultt) {
                if (resultt.userId===undefined){
                    alert("请选择昵称");
                    return;
                }
                qixia('GET', 'http://101.34.184.45/addGameScore/' + resultt.userId + '/' + result.gameId,
                false, addGameScoreRs);
        }); });
    }

function qi() {
   console.log("我永远爱你");
}
function qixia(method, url, interactive, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open(method, url);
xhr.onload = requestComplete;
  xhr.send();
function requestComplete() {
  // console.log('requestComplete', this.status, this.response);
  if ( ( this.status < 200 || this.status >=300 ) ) {

  } else {
    callback(null, this.status, this.response);
  }
}
}

function setIcon() {
    chrome.storage.local.get(['icon0'], function(result) {
        chrome.storage.local.get(['icon1'], function(resultt) {
            chrome.storage.local.get(['icon2'], function(resulttt) {
                var a,b,c;
                a=result.icon0;
                b=resultt.icon1;
                c=resulttt.icon2;
                if (result.icon0===undefined){
                     a=0;
                }
                if(resultt.icon1===undefined){
                    b=0;
                }
                if(resulttt.icon2===undefined) {
                    c=0;
                }
                    document.getElementById("icon").innerText=
                        "诺尔儿："+a+" 刻晴："+b+"  神里凌华："+c;

        }); }); });
    }

function getDataFromCache() {
    setIcon();
        chrome.storage.local.get(['userId'], function(result) {
            var userId=result.userId;
            if(result.userId!==undefined){
                document.getElementById("changeName").style.visibility="hidden";
                document.getElementById("details1").innerText=
                    "昵称："+userId;
            }else{
                document.getElementById("details1").innerText=
                    "昵称：请选择昵称!"
                document.getElementById("details1").style.color="#DDA0DD";

            }
            chrome.storage.local.get(['score'], function(resultt) {
                var score=resultt.score;
                if(resultt.score===undefined){
                    score="0";
                }
                chrome.storage.local.get(['rank'], function(resulttt) {
                    var rank=resulttt.rank;
                    if(resulttt.rank===undefined){
                        rank="";
                    }
                    chrome.storage.local.get(['bodyPX'], function(resultttt) {
                        var bodyPX=resultttt.bodyPX;
                        if(bodyPX===undefined){
                            chrome.storage.local.set({bodyPX: 320}, function () {
                            });
                            bodyPX=320;
                        }
                        num=bodyPX/80-1;

                    document.getElementById("details2").innerText=
                            "难度："+bodyPX/80+"*"+bodyPX/80+" " +
                            "总数："+score +"  排行榜："+rank;

        if (resultttt.bodyPX===undefined){
            document.body.style.width="320px";
            document.body.style.height="420px";
            document.getElementById("four").style.display="none";
            document.getElementById("five").style.display="";
            document.getElementById("three").style.display="";
            num=3;
        }else{
            document.body.style.height=(Number(resultttt.bodyPX)+140)+"px";
            document.body.style.width=resultttt.bodyPX+"px";
            num=resultttt.bodyPX/80-1;
            if(num===2){
                document.getElementById("three").style.display="none";
                document.getElementById("four").style.display="";
                document.getElementById("five").style.display="";
            } else if(num===3){
                document.getElementById("four").style.display="none";
                document.getElementById("five").style.display="";
                document.getElementById("three").style.display="";
            } else if(num===4){
                document.getElementById("five").style.display="none";
                document.getElementById("three").style.display="";
                document.getElementById("four").style.display="";
            }

        }
    });});});});
    }



function addGameScoreRs(error, status, response) {
        if (!error && status == 200) {
            var res = JSON.parse(response);
            chrome.storage.local.get(['bodyPX'], function(result) {
                document.getElementById("details1").innerText=
                    "昵称："+res.UserId;
                document.getElementById("details2").innerText =
                    "难度："+result.bodyPX/80+"*"+result.bodyPX/80+" 总数：" + res.Score + "  排行榜：" + res.Rank;
            });
            chrome.storage.local.set({userId: userId}, function () {
            });
            chrome.storage.local.set({score: res.Score}, function () {
            });
            chrome.storage.local.set({rank: res.Rank}, function () {
            });
        }
    }

    function getGameRankRs(error, status, response) {
        if (!error && status == 200) {
            var result = JSON.parse(response);
            document.getElementById("details2").innerText=
                " 难度："+result.GameId +
                "总数："+result.Score +"  排行榜："+result.Rank;
        }}

    })();




window.onload = gh.onload;